package com.wxscrmplus.devtool.service.impl;

import cn.dev33.satoken.context.SaHolder;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxscrmplus.common.constant.CacheConstants;
import com.wxscrmplus.common.constant.CacheNames;
import com.wxscrmplus.common.constant.UserConstants;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.wxscrmplus.common.core.domain.entity.DevDictData;
import com.wxscrmplus.common.core.domain.entity.DevDictType;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.core.service.DictService;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.StreamUtils;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.common.utils.redis.CacheUtils;
import com.wxscrmplus.common.utils.spring.SpringUtils;
import com.wxscrmplus.devtool.domain.DevModular;
import com.wxscrmplus.devtool.mapper.DevDictDataMapper;
import com.wxscrmplus.devtool.mapper.DevDictTypeMapper;
import com.wxscrmplus.devtool.mapper.DevModularMapper;
import com.wxscrmplus.devtool.service.IDevDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author www.wxscrmplus.com
 */
@RequiredArgsConstructor
@Service
public class DevDictTypeServiceImpl implements IDevDictTypeService, DictService {

    private final DevDictTypeMapper baseMapper;
    private final DevDictDataMapper dictDataMapper;
    private final DevModularMapper modularMapper;

    @Override
    public TableDataInfo<DevDictType> selectPageDictTypeList(DevDictType dictType, PageQuery pageQuery) {
        Map<String, Object> params = dictType.getParams();
        LambdaQueryWrapper<DevDictType> lqw = new LambdaQueryWrapper<DevDictType>()
            .like(StringUtils.isNotBlank(dictType.getDictName()), DevDictType::getDictName, dictType.getDictName())
            .eq(StringUtils.isNotBlank(dictType.getStatus()), DevDictType::getStatus, dictType.getStatus())
            .eq(ObjectUtil.isNotEmpty(dictType.getModularId()), DevDictType::getModularId, dictType.getModularId())
            .like(StringUtils.isNotBlank(dictType.getDictType()), DevDictType::getDictType, dictType.getDictType())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                DevDictType::getCreateTime, params.get("beginTime"), params.get("endTime"));
        Page<DevDictType> page = baseMapper.selectPage(pageQuery.build(), lqw);
        for (DevDictType record : page.getRecords()) {
            DevModular devModular = modularMapper.selectById(record.getModularId());
            if (ObjectUtil.isNotNull(devModular)) {
                record.setModularName(devModular.getName());
            }
        }
        return TableDataInfo.build(page);
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<DevDictType> selectDictTypeList(DevDictType dictType) {
        Map<String, Object> params = dictType.getParams();
        return baseMapper.selectList(new LambdaQueryWrapper<DevDictType>()
// d4858c91cf03db6ac57b3c5ea798d26b
            .like(StringUtils.isNotBlank(dictType.getDictName()), DevDictType::getDictName, dictType.getDictName())
            .eq(StringUtils.isNotBlank(dictType.getStatus()), DevDictType::getStatus, dictType.getStatus())
            .like(StringUtils.isNotBlank(dictType.getDictType()), DevDictType::getDictType, dictType.getDictType())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                DevDictType::getCreateTime, params.get("beginTime"), params.get("endTime")));
    }

    /**
     * 获取模块字典类型（模块不为空则获取模块下的数据，否则获取全部）
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<DevDictType> selectDictTypeByModularId(Long modularId) {
        List<Long> list = new ArrayList<>(Collections.singletonList(1L));
        if (ObjectUtil.isNotNull(modularId)) {
            list.add(modularId);
        }
        return baseMapper.selectList(Wrappers.query(new DevDictType()).lambda()
            .in(DevDictType::getModularId, list));
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Cacheable(cacheNames = CacheNames.SYS_DICT, key = "#dictType")
    @Override
    public List<DevDictData> selectDictDataByType(String dictType) {
        List<DevDictData> dictDatas = dictDataMapper.selectDictDataByType(dictType);
        if (CollUtil.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public DevDictType selectDictTypeById(Long dictId) {
        DevDictType devDictType = baseMapper.selectById(dictId);
        DevModular devModular = modularMapper.selectById(devDictType.getModularId());
        if (ObjectUtil.isNotNull(devModular)) {
            devDictType.setModularName(devModular.getName());
        }
        return devDictType;
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Cacheable(cacheNames = CacheNames.SYS_DICT, key = "#dictType")
    @Override
    public DevDictType selectDictTypeByType(String dictType) {
        return baseMapper.selectById(new LambdaQueryWrapper<DevDictType>().eq(DevDictType::getDictType, dictType));
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            DevDictType dictType = selectDictTypeById(dictId);
            if (dictDataMapper.exists(new LambdaQueryWrapper<DevDictData>()
                .eq(DevDictData::getDictType, dictType.getDictType()))) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            CacheUtils.evict(CacheNames.SYS_DICT, dictType.getDictType());
        }
        baseMapper.deleteBatchIds(Arrays.asList(dictIds));
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        List<DevDictData> dictDataList = dictDataMapper.selectList(
            new LambdaQueryWrapper<DevDictData>().eq(DevDictData::getStatus, UserConstants.DICT_NORMAL));
        Map<String, List<DevDictData>> dictDataMap = StreamUtils.groupByKey(dictDataList, DevDictData::getDictType);
        dictDataMap.forEach((k, v) -> {
            List<DevDictData> dictList = StreamUtils.sorted(v, Comparator.comparing(DevDictData::getDictSort));
            CacheUtils.put(CacheNames.SYS_DICT, k, dictList);
        });
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        CacheUtils.clear(CacheNames.SYS_DICT);
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#dict.dictType")
    @Override
    public List<DevDictData> insertDictType(DevDictType dict) {
        int row = baseMapper.insert(dict);
        if (row > 0) {
            return new ArrayList<>();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#dict.dictType")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DevDictData> updateDictType(DevDictType dict) {
        DevDictType oldDict = baseMapper.selectById(dict.getDictId());
        dictDataMapper.update(null, new LambdaUpdateWrapper<DevDictData>()
            .set(DevDictData::getDictType, dict.getDictType())
            .eq(DevDictData::getDictType, oldDict.getDictType()));
        int row = baseMapper.updateById(dict);
        if (row > 0) {
            CacheUtils.evict(CacheNames.SYS_DICT, oldDict.getDictType());
            return dictDataMapper.selectDictDataByType(dict.getDictType());
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(DevDictType dict) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<DevDictType>()
            .eq(DevDictType::getDictType, dict.getDictType())
            .ne(ObjectUtil.isNotNull(dict.getDictId()), DevDictType::getDictId, dict.getDictId()));
        return !exist;
    }

    /**
     * 根据字典类型和字典值获取字典标签
     *
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @param separator 分隔符
     * @return 字典标签
     */
    @SuppressWarnings("unchecked cast")
    @Override
    public String getDictLabel(String dictType, String dictValue, String separator) {
        // 优先从本地缓存获取
        List<DevDictData> datas = (List<DevDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
        if (ObjectUtil.isNull(datas)) {
            datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
            SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
        }

        Map<String, String> map = StreamUtils.toMap(datas, DevDictData::getDictValue, DevDictData::getDictLabel);
        if (StringUtils.containsAny(dictValue, separator)) {
            return Arrays.stream(dictValue.split(separator))
                .map(v -> map.getOrDefault(v, StringUtils.EMPTY))
                .collect(Collectors.joining(separator));
        } else {
            return map.getOrDefault(dictValue, StringUtils.EMPTY);
        }
    }

    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param dictType  字典类型
     * @param dictLabel 字典标签
     * @param separator 分隔符
     * @return 字典值
     */
    @SuppressWarnings("unchecked cast")
    @Override
    public String getDictValue(String dictType, String dictLabel, String separator) {
        // 优先从本地缓存获取
        List<DevDictData> datas = (List<DevDictData>) SaHolder.getStorage().get(CacheConstants.SYS_DICT_KEY + dictType);
        if (ObjectUtil.isNull(datas)) {
            datas = SpringUtils.getAopProxy(this).selectDictDataByType(dictType);
            SaHolder.getStorage().set(CacheConstants.SYS_DICT_KEY + dictType, datas);
        }

        Map<String, String> map = StreamUtils.toMap(datas, DevDictData::getDictLabel, DevDictData::getDictValue);
        if (StringUtils.containsAny(dictLabel, separator)) {
            return Arrays.stream(dictLabel.split(separator))
                .map(l -> map.getOrDefault(l, StringUtils.EMPTY))
                .collect(Collectors.joining(separator));
        } else {
            return map.getOrDefault(dictLabel, StringUtils.EMPTY);
        }
    }

}
